<!--
盲审抽取比例设置新增
-->
<template>
    <div>
        <div>
            <el-form :model="form" ref="form" label-suffix="：" :rules="rules" label-width="85px">
                <el-row :gutter="10" class="group_style" v-if="showType === 'all' || (showType !== 'teacher' && showType !== 'student')">
                    <el-col :span="12">
                        <el-form-item :label="$t('label.grade')" prop="grade">
                          <el-date-picker v-model="form.grade" value-format="yyyy" type="year" placeholder="" :clearable="true" style="width: 100%" />
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="group_style" v-if="showType === 'all' || showType === 'type'">
                    <h2>{{$t('paperBlindTrial.byStuType')}}</h2>
                    <el-col :span="12">
                        <el-form-item :label="$t('label.trainingLevel')" prop="eduLevel">
                          <DictSelect v-model="form.eduLevel" @change="(value)=>typeChange(value, 'eedsRate')" :data="options.eduLevel" :clearable="true" ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('label.trainingCategory')" prop="eduMode">
                            <DictSelect v-model="form.eduMode" :filterable="true"  @change="(value)=>typeChange(value, 'eedsRate')" :data="options.eduMode" :clearable="true" v-clearreadonly></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('label.degreeCategory')" prop="degreeType">
                            <DictSelect v-model="form.degreeType" @change="(value)=>typeChange(value, 'eedsRate')" :data="options.degreeType" :clearable="true" ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('label.formLearning')" prop="studyForm">
                            <DictSelect v-model="form.studyForm" @change="(value)=>typeChange(value, 'eedsRate')" :data="options.studyForm" :clearable="true" ></DictSelect>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('paperBlindTrial.extractLabel')" prop="eedsRate">
                          <el-input v-model="form.eedsRate" :placeholder="$t('common.pla.pleaseInput')" maxlength="20" :clearable="true">
                            <template slot="append">%</template>
                          </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="group_style" v-if="showType === 'all' || showType === 'major'">
                    <h2>{{$t('paperBlindTrial.byCollegeOrMajor')}}</h2>
                    <el-col :span="12">
                      <el-form-item :label="$t('label.college')">
                        <el-select
                          v-model="form.academyCode"
                          style="width: 100%;"
                          clearable
                          filterable
                          :placeholder="$t('common.text.all')"
                          @change="academyChange"
                          v-clearreadonly
                        >
                          <el-option
                              v-for="item in options.academyCode"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                          />
                        </el-select>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item :label="$t('label.major')">
                        <el-select
                          @change="(value)=>typeChange(value, 'majorRate')"
                          v-model="form.majorCode"
                          filterable
                          :placeholder="$t('common.text.all')"
                          style="width: 100%;"
                          :clearable="true"
                          v-clearreadonly
                        >
                          <el-option
                            v-for="item in majorList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value"
                          />
                        </el-select>
                        <MyMajor v-show="false" :faculty="form.academyCode" :filterable="true" @load-done="saveMajorList" :grade="form.grade"> </MyMajor>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('paperBlindTrial.extractLabel')" prop="majorRate">
                          <el-input v-model="form.majorRate" :placeholder="$t('common.pla.pleaseInput')" maxlength="20" :clearable="true">
                            <template slot="append">%</template>
                          </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="group_style" v-if="showType === 'all' || showType === 'teacher'">
                    <h2>{{$t('paperBlindTrial.byTeacher')}}</h2>
                    <el-col :span="12">
                        <el-form-item :label="$t('achievementApply.teacherName')" prop="stuTutorNo" >
                          <!-- <TeacherSelect v-model="form.stuTutorNo" :conditionNotNull="false"
                          value="code" :clearable="true"> </TeacherSelect> -->
                          <el-select
                            ref="filterSelect"
                            v-model="form.stuTutorNo"
                            :remote-method="selectUser"
                            :placeholder="$t('preDefense.teacherNameTips')"
                            filterable
                            remote
                            style="width: 100%;"
                            :clearable="true"
                            @change="stuTutorChange"
                            v-clearreadonly
                          >
                            <el-option
                              v-for="item in users"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            />
                          </el-select>
                        </el-form-item>
                    </el-col>
                    <el-col :span="12">
                        <el-form-item :label="$t('paperBlindTrial.extractLabel')" prop="stuTutorRate">
                          <el-input v-model="form.stuTutorRate" :placeholder="$t('common.pla.pleaseInput')" maxlength="20" :clearable="true">
                            <template slot="append">%</template>
                          </el-input>
                        </el-form-item>
                    </el-col>
                </el-row>
                <el-row :gutter="10" class="group_style" v-if="showType === 'all' || showType === 'student'">
                    <h2>{{$t('paperBlindTrial.mustList')}}</h2>
                    <el-col :span="12">
                        <el-form-item :label="$t('paperBlindTrial.students')" prop="stuNos">
                          <el-select
                            v-model="form.stuNos"
                            :remote-method="selectStu"
                            :placeholder="$t('common.pla.pleaseSelect')"
                            filterable
                            remote
                            style="width: 100%;"
                            multiple
                            :clearable="true"
                          >
                            <el-option
                              v-for="item in students"
                              :key="item.value"
                              :label="item.label"
                              :value="item.value"
                            />
                          </el-select>
                          <!-- <StudentSelect
                              v-model="form.stuNos"
                              ref="classStudentRef"
                              :multiple="true"
                          ></StudentSelect> -->
                        </el-form-item>
                    </el-col>
                </el-row>
            </el-form>
        </div>
    </div>
</template>

<script>
import { categoryAdd, majorAdd, tutorAdd, tutorEdit, majorEdit, categoryEdit,
categoryGetDetail, majorGetDetail, tutorGetDetail, drawRatioAdd } from "common/src/api/paperBlindTrial";
import commonMixins from 'common/src/views/practiceManagement/commonMixins';
import MyMajor from "common/src/views/administrator/undergraduateTutor/component/MyMajor";
import { findTeacherInfoList, findStuInfoListForSelect } from 'common/src/api/studentinfo';
import { getAllMajorList, getMajorList } from "common/src/api/resource/course";
import UTILS from "common/src/utils/utils";
import mixin from 'common/src/mixins/index';
export default {
    components: {
      MyMajor
    },
    mixins: [commonMixins,mixin],
    props: {
      objs: {
        type: Object,
      },
      options: {
        type: Object,
      },
      showType: {
        type: String
      }
    },
    data() {
        return {
            form: {
              "grade": "",
              "eduLevel": "",
              "eduMode": "",
              "degreeType": "",
              "studyForm": "",
              "eedsRate": null,
              "stuNos": [],
              "stuTutorNo": "",
              "stuTutorRate": null,
              "majorRate": null,
              "academyCode": '',
              "majorCode": '',
            },
            rules: {
              grade: [],
              eedsRate: [],
              majorRate: [],
              stuTutorRate: [],
            },
            users: [], // 导师信息
            students: [], // 学生信息
            majorList: [], // 专业信息
            lastAcademyCode: '' // 上一次学院数据
        };
    },
    computed: {

    },
    mounted() {
      // this.getListData();
      // if (this.objs.ids && this.objs.ids !== '') {
      //   this.getDetail();
      // }
      this.majorList = !this.global.isAcdemicDean ? this.options.majorAll : [];
      if (this.objs.ids && this.objs.ids !== '') {
        // 类别查询
        if (this.showType === 'type') {
          this.getCategoryDetail();
        }
        // 专业
        if (this.showType === 'major') {
          this.getMajorDetail();
        }
        // 导师
        if (this.showType === 'teacher') {
          this.getTutorDetail();
        }
      }
    },
    methods: {
      save(flag) { // flag = edit 修改
        this.$refs.form.validate((valid) => {
          if (valid) {
            let param = Object.assign({}, this.form);
            if(this.showType==='all') { // 全部增加
              let stuNoList = this.form.stuNos;
              let stuTutorItem = this.form.stuTutorNo;
              let stuNames = [];
              let stuNos = [];
              param.stuTutorName = stuTutorItem&&stuTutorItem!==''?stuTutorItem.split(',')[1]:'';
              param.stuTutorNo = stuTutorItem&&stuTutorItem!==''?stuTutorItem.split(',')[0]:'';
              stuNoList.forEach(item=>{
                let itemList = item.split(',');
                stuNames.push(itemList[1]);
                stuNos.push(itemList[0]);
              });
              param.stuNos = stuNos.join(',');
              param.stuNames = stuNames.join(',');
              drawRatioAdd(param).then(res => {
                if (flag === 'edit') {
                  this.$message.success(this.$t('achievementApply.editSuccessfully'));
                } else {
                  this.$message.success(this.$t('message.addSuccess'));
                }
                this.$emit('emit:back');
              });
            }
            if (this.showType==='type') { //类别
              if (UTILS.isEmpty(param.eduLevel) && UTILS.isEmpty(param.eduMode)
                && UTILS.isEmpty(param.degreeType) && UTILS.isEmpty(param.studyForm)) {
                this.$message.error(this.$t('paperBlindTrial.studentTypeEmpty'));
                return;
              }
              param.rate = this.form.eedsRate;
              if (flag === 'edit') {
                categoryEdit(param).then(res=>{
                  this.$message.success(this.$t('achievementApply.editSuccessfully'));
                  this.$emit('emit:back');
                });
              } else {
                categoryAdd(param).then(res=>{
                  this.$message.success(this.$t('message.addSuccess'));
                  this.$emit('emit:back');
                });
              }
            }
            if (this.showType==='major') { //专业
              if (UTILS.isEmpty(param.academyCode) && UTILS.isEmpty(param.majorCode)) {
                this.$message.error(this.$t('paperBlindTrial.academyCodeEmpty'));
                return;
              }
              param.rate = this.form.majorRate;
              param.majorName=(param.majorCode&&this.majorList.filter(v=>v.value==param.majorCode)[0].label) || '';
              param.academyCodeI18n=(param.academyCode && this.options.academyCode.filter(v=>v.value==param.academyCode)[0].label) || '';
              if (flag === 'edit') {
                majorEdit(param).then(res=>{
                  this.$message.success(this.$t('achievementApply.editSuccessfully'));
                  this.$emit('emit:back');
                });
              } else {
                majorAdd(param).then(res=>{
                  this.$message.success(this.$t('message.addSuccess'));
                  this.$emit('emit:back');
                });
              }
            }
            if (this.showType==='teacher') { //导师
              if (UTILS.isEmpty(param.stuTutorNo) && UTILS.isEmpty(param.majorCode)) {
                this.$message.error(this.$t('paperBlindTrial.tutorNoEmpty'));
                return;
              }
              let stuTutorItem = this.form.stuTutorNo;
              param.rate = this.form.stuTutorRate;
              if (flag === 'edit') {
                let editItem = stuTutorItem&&stuTutorItem!==''?stuTutorItem.split('('):[];
                param.stuTutorName = editItem[0];
                param.stuTutorNo = editItem.length>0?editItem[1].split(')')[0]:'';
                tutorEdit(param).then(res=>{
                  this.$message.success(this.$t('achievementApply.editSuccessfully'));
                  this.$emit('emit:back');
                });
              } else {
                param.stuTutorName = stuTutorItem&&stuTutorItem!==''?stuTutorItem.split(',')[1]:'';
                param.stuTutorNo = stuTutorItem&&stuTutorItem!==''?stuTutorItem.split(',')[0]:'';
                tutorAdd(param).then(res=>{
                  this.$message.success(this.$t('message.addSuccess'));
                  this.$emit('emit:back');
                });
              }
            }
          }
        });
      },
      // 根据id获取规则详情
      // 类型
      getCategoryDetail() {
        categoryGetDetail(this.objs.ids).then(res=>{
          if (res.code === 200) {
            let resultData = res.data;
            this.form = {
              id: resultData.id,
              "grade": resultData.grade,
              "eduLevel": resultData.eduLevel,
              "eduMode": resultData.eduMode,
              "degreeType": resultData.degreeType,
              "studyForm": resultData.studyForm,
              "eedsRate": resultData.rate,
              "manageDeptId": resultData.manageDeptId,
            };
            this.typeChange(resultData.eduLevel || resultData.eduMode || resultData.degreeType || resultData.studyForm, 'eedsRate');
          }
        });
      },
      // 导师
      getTutorDetail(){
        tutorGetDetail(this.objs.ids).then(res=>{
           if (res.code === 200) {
            let resultData = res.data;
            this.form = {
              id: resultData.id,
              "stuTutorNo": resultData.stuTutorName+'('+resultData.stuTutorNo+')',
              "stuTutorRate": resultData.rate,
              "manageDeptId": resultData.manageDeptId,
            }
            this.stuTutorChange(resultData.stuTutorNo);
           }
        });
      },
      // 专业
      getMajorDetail() {
        majorGetDetail(this.objs.ids).then(res=>{
          if (res.code === 200) {
            let resultData = res.data;
            this.form = {
              id: resultData.id,
              grade: resultData.grade,
              "majorCode": resultData.majorCode,
              "academyCode": resultData.academyCode,
              majorRate: resultData.rate,
              "manageDeptId": resultData.manageDeptId,
            };
            this.lastAcademyCode = resultData.academyCode;
            this.typeChange(resultData.majorCode, 'majorRate');
            this.academyChange(resultData.academyCode, 'majorRate');
          }
        });
      },
      getDetail () {
        drawRatioGetDetail(this.objs.ids).then(res => {
          let resultData = res.data;
          if (res.code === 200) {
            let stuList = [];
            let stuNoList = resultData.stuNos.length > 0 ? resultData.stuNos.split(',') : [];
            let stuNameList = resultData.stuNames.length > 0 ? resultData.stuNames.split(',') : [];
            let subjectCode = '';
            let stuTutorNo = '';
            if (resultData.subjectCode&&resultData.subjectCode!=='') {
              subjectCode = resultData.subjectCode+','+resultData.subjectName;
            }
            if (resultData.stuTutorNo&&resultData.stuTutorNo!=='') {
              stuTutorNo = resultData.stuTutorNo+','+resultData.stuTutorName;
              this.users.push({
                label: resultData.stuTutorName + '(' + resultData.stuTutorNo + ')',
                value: stuTutorNo,
              });
            }
            stuNoList.forEach((item, index)=>{
              let itemKey = item+','+stuNameList[index];
              let obj = {
                label: stuNameList[index] + '(' + item + ')',
                value: itemKey,
              };
              stuList.push(itemKey);
              this.students.push(obj);
            });
            this.form = {
              id: resultData.id,
              "grade": resultData.grade,
              "eduLevel": resultData.eduLevel,
              "eduMode": resultData.eduMode,
              "degreeType": resultData.degreeType,
              "studyForm": resultData.studyForm,
              "eedsRate": resultData.eedsRate,
              "stuNos": stuList,
              "stuTutorNo": stuTutorNo,
              "stuTutorRate": resultData.stuTutorRate,
              "subjectCode": subjectCode,
              "majorRate": resultData.majorRate,
            };
            this.typeChange(resultData.eduLevel || resultData.eduMode || resultData.degreeType || resultData.studyForm, 'eedsRate');
            this.typeChange(resultData.subjectCode, 'majorRate');
            this.stuTutorChange(resultData.stuTutorNo);
          }
        });
      },
      //可用TeacherSelect通用组件替换
      selectUser(query) {
        if (!query) return
        const data = {
          condition: query,
          pageNum_: 1,
          pageSize_: 10
        };
        this.loading = true
        findTeacherInfoList(data)
          .then(res => {
              this.loading = false
              if (res.code == 200) {
                  this.users = this.transData(res.data.list, 'name', 'code')
              } else throw res.code
          })
          .catch(error => {
              this.loading = false
              this.$message({
                  type: 'error',
                  message: '查询用户出错'
              })
          })
      },
      transData(list, name, code) {
        return list.map((item, index, array) => {
          return {
              label: item[name] + '(' + item[code] + ')',
              value: item[code]+','+item[name],
          }
        })
      },
      // 查询学生信息接口
      selectStu (query) {
        if (!query) return;
        const data = {
          name: query,
          // teacherCodeAndName: this.form.stuTutorNo,  // 导师id
          pageNum_: 1,
          pageSize_: 50
        }
        this.loading = true
        findStuInfoListForSelect(data)
          .then(res => {
            this.loading = false
          if (res.code == 200) {
              this.students = this.transData(res.data.list, 'name', 'studentId')
            } else throw res.code
          })
          .catch(error => {
              this.loading = false
              this.$message({
                  type: 'error',
                  message: '查询用户出错'
              })
          })
      },
      // 校验输入的抽取比例值
      validateRate (rule, value, callback) {
        let reng = /^[1-9][0-9]*$/ // 正整数
        if (!value || value.length === 0) {
          return callback(new Error(this.$t('inputPlaceholder')));
        }
        if (!reng.test(value)) {
          return callback(new Error(this.$t('paperBlindTrial.moreThenZero')));
        }
        if (Number(value) > 100) {
          return callback(new Error(this.$t('paperBlindTrial.extractTips')));
        }
        return callback();
      },
      // 获取一级学科/专业领域
      getListData () {
        // 一级学科（学术型） type： 1
        // 专业领域（专业型） type： 2
        getAllMajorList({
          level: 2,
          type: 1,
          page: false
        }).then(res => {
          if (res.code == 200) {
            this.options.subjectCode = res.data.list.map(c => {
              return {
                  label: c.name,
                  value: c.id+','+c.name,
              };
            });
          }
        });
      },
      // 取值改变方法，需要校验年级和对应抽取比例
      typeChange (value, key) {
        if (value&&value!=='') {
          // this.rules.grade = [{ required: true, message: this.$t('message.plzSelect'), trigger: 'change' }];
          this.rules[key] = [{ required: true, validator: this.validateRate, trigger: 'change' }];
          return;
        }
        // this.$refs.form.clearValidate(['grade', key]);
        if (!this.form.eduLevel && !this.form.eduMode && !this.form.degreeType && !this.form.studyForm
        && !this.form.academyCode && !this.form.majorCode) {
          // this.rules.grade = [];
        }
        if (key === 'eedsRate' && (this.form.eduLevel || this.form.eduMode || this.form.degreeType || this.form.studyForm)) {
          return;
        }
        if (key === 'majorRate' && (this.form.academyCode || this.form.majorCode)) {
          return;
        }
        this.rules[key] = [];
      },
      academyChange(value) {
        this.majorList = !this.global.isAcdemicDean ? this.options.majorAll : [];
        if (this.lastAcademyCode !== value) {
          this.form.majorCode = '';
        }
        this.lastAcademyCode = value;
        if (value&&value!=='') {
          // this.rules.grade = [{ required: true, message: this.$t('message.plzSelect'), trigger: 'change' }];
          this.rules.majorRate = [{ required: true, validator: this.validateRate, trigger: 'change' }];
          return;
        }
        if (this.form.majorCode && this.form.majorCode !== '') {
          return;
        }
        this.rules[key] = [];
      },
      // 导师值改变方法判断
      stuTutorChange (value) {
        if (value&&value!=='') {
          this.rules.stuTutorRate = [{ required: true, validator: this.validateRate, trigger: 'change' }];
          return;
        }
        this.$refs.form.clearValidate(['stuTutorRate']);
        this.rules.stuTutorRate = [];
      },
      // 保存专业数据
      saveMajorList(data){
        if (!this.global.isAcdemicDean) {
          this.majorList = this.form.academyCode?data:this.options.majorAll;
        } else {
          this.majorList = data;
        }
      },
    },
};
</script>

<style scoped lang="scss">
.color {
    &_no {
        color: #ccc;
        margin-right: 5px;
    }
    &_yes {
        color: #222;
        margin-left: 5px;
    }
}
.group_style {
  border-bottom: solid #ccc 2px;
  margin-bottom: 10px;
}
</style>
